<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>题目展示系统</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    *::-webkit-scrollbar {
      width: 0.5rem;
      height: 0.5rem;
    }

    *::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 0.5rem;
    }

    *::-webkit-scrollbar-thumb {
      background: #3498db;
      border-radius: 0.5rem;
    }

    *::-webkit-scrollbar-thumb:hover {
      background: #2980b9;
    }


    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f7f9fc;
      color: #333;
      line-height: 1.6;
      padding: 20px;
    }

    header {
      text-align: center;
      margin-bottom: 30px;
    }

    h1 {
      color: #2c3e50;
      font-size: 2rem;
    }

    .search-box {
      display: flex;
      justify-content: center;
      margin-bottom: 30px;
    }

    .search-box input {
      width: 80%;
      max-width: 500px;
      padding: 12px 20px;
      font-size: 1rem;
      border: 2px solid #ddd;
      border-radius: 50px;
      outline: none;
      transition: all 0.3s ease;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .search-box input:focus {
      border-color: #3498db;
      box-shadow: 0 4px 15px rgba(52, 152, 219, 0.2);
    }

    .question-container {
      display: flex;
      flex-direction: column;
      gap: 20px;
      max-width: 900px;
      margin: 0 auto;
    }

    .question-card {
      background: white;
      border-radius: 12px;
      padding: 20px 25px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      transition: transform 0.2s ease, box-shadow 0.2s ease;
      border-left: 5px solid #3498db;
    }

    .question-card:hover {
      transform: translateY(-3px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
    }

    .question-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
    }

    .question-index {
      font-weight: bold;
      color: #2980b9;
      font-size: 1.1em;
    }

    .question-type {
      font-size: 0.9em;
      color: #7f8c8d;
      background: #ecf0f1;
      padding: 4px 10px;
      border-radius: 20px;
    }

    .question-text {
      font-size: 1.1em;
      margin-bottom: 15px;
      color: #2c3e50;
    }

    .options {
      list-style: none;
    }

    .option-item {
      padding: 8px 15px;
      margin: 6px 0;
      background: #f8f9fa;
      border-radius: 8px;
      border-left: 3px solid #bdc3c7;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    .option-item strong {
      color: #e74c3c;
      min-width: 20px;
      display: inline-block;
    }

    .hidden {
      display: none;
    }

    @media (max-width: 600px) {
      body {
        padding: 10px;
      }

      h1 {
        font-size: 1.6rem;
      }

      .search-box input {
        width: 95%;
        padding: 10px 15px;
      }

      .question-card {
        padding: 16px;
      }

      .question-text {
        font-size: 1rem;
      }
    }
  </style>
</head>

<body>
  <header>
    <h1>📝 题目展示与搜索系统</h1>
  </header>

  <div class="search-box">
    <input type="text" id="searchInput" placeholder="🔍 搜索题目或选项中的关键词..." />
  </div>

  <div style="text-align: center; margin-bottom: 30px;">
    <label for="fileInput"
      style="cursor: pointer; background: #2980b9; color: white; padding: 10px 20px; border-radius: 50px; font-size: 0.9rem; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
      📂 导入本地题目文件
    </label>
    <input type="file" id="fileInput" accept=".json" style="display: none;" />
  </div>

  <div class="question-container" id="questionContainer">
    <!-- 题目将通过 JavaScript 动态插入 -->
  </div>

  <script>
    // 加载 JSON 数据并渲染题目
    document.addEventListener("DOMContentLoaded", async () => {
      let questions = [
        {
          "index": 1,
          "questionType": "单选题",
          "questionName": "下列关于HTTP的PUT请求方法，说法错误的是（）？",
          "options": {
            "A": "PUT请求的参数也要在HTTP请求的消息主体中发送",
            "B": "在RESTful设计规范中，一般POST方法代表新增，PUT方法代表整体更新",
            "C": "PUT请求方法是在HTTP1.1版本中新增的",
            "D": "默认情况下，PUT请求也可以完成表单数据的提交"
          },
          "yourAnswer": "A",
          "correctAnswer": "D",
          "analysis": null
        },
        {
          "index": 2,
          "questionType": "单选题",
          "questionName": "下面关于 MyBatis 的说法错误的是（）",
          "options": {
            "A": "MyBatis 中实现动态 SQL 的原理是动态代理机制",
            "B": "MyBatis 一级缓存是指 SqlSession 级别的缓存，如果两次中间出现 commit 操作 （查询、修改、添加、删除），则本 sqlsession\n                    中的一级缓存区域全部清空",
            "C": "MyBatis 通过动态代理使 Mapper 接口能运行起来，即为接口生成代理对象将 sql 查询到结果映射成 POJO",
            "D": "MyBatis 二级缓存是指可以跨 SqlSession 的缓存，是 mapper 级别的缓存"
          },
          "yourAnswer": "B",
          "correctAnswer": "B",
          "analysis": null
        }
      ];

      const container = document.getElementById("questionContainer");
      renderQuestions(questions);

      // 搜索逻辑
      document.getElementById("searchInput").addEventListener("input", (e) => {
        const keyword = e.target.value.trim().toLowerCase();
        if (!keyword) {
          document.querySelectorAll(".question-card").forEach(el => el.classList.remove("hidden"));
          return;
        }

        questions.forEach((q, idx) => {
          const card = container.children[idx];
          const content = `
            ${q.questionName} 
            ${Object.values(q.options).join(" ")}
          `.toLowerCase();

          if (content.includes(keyword)) {
            card.classList.remove("hidden");
          } else {
            card.classList.add("hidden");
          }
        });
      });

      function escapeHtml(unsafe) {
        return unsafe
          .toString()
          .replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;")
          .replace(/"/g, "&quot;")
          .replace(/'/g, "&#039;");
      }

      function renderQuestions(list) {
        container.innerHTML = "";
        list.forEach(q => {
          const card = document.createElement("div");
          card.className = "question-card";

          let optionsHtml = "";
          for (let key in q.options) {
            // 高亮用户选择的答案
            const isYourAnswer = key === q.yourAnswer;
            const isCorrectAnswer = key === q.correctAnswer;

            let bgColor = "#f8f9fa";
            if (isYourAnswer && isCorrectAnswer) {
              bgColor = "#d4edda"; // 绿色：答对
            } else if (isYourAnswer && !isCorrectAnswer) {
              bgColor = "#f8d7da"; // 红色：答错
            }

            optionsHtml += `
              <li class="option-item" style="background-color: ${bgColor}; border-left-color: ${isYourAnswer ? '#e74c3c' : '#bdc3c7'
              }">
                <strong>${key}.</strong> ${escapeHtml(q.options[key])}
                ${isYourAnswer ? '<span style="color:#e74c3c; font-weight:bold; margin-left: 10px;">← 你的回答</span>' : ''}
              </li>`;
          }

          // 判断答题结果
          const isCorrect = q.yourAnswer === q.correctAnswer;
          const resultText = isCorrect
            ? '<span style="color: #27ae60; font-weight: bold;">✅ 回答正确</span>'
            : `<span style="color: #e74c3c; font-weight: bold;">❌ 回答错误</span>，正确答案是：<strong style="color: #2980b9;">${q.correctAnswer}</strong>`;

          card.innerHTML = `
            <div class="question-header">
              <span class="question-index">第 ${q.index} 题</span>
              <span class="question-type">${q.questionType}</span>
            </div>
            <div class="question-text">${q.questionName}</div>
            <ul class="options">
              ${optionsHtml}
            </ul>
            <div class="answer-result" style="margin-top: 15px; padding: 10px; background-color: ${isCorrect ? '#f6ffed' : '#fff7f7'
            }; border-radius: 8px; font-size: 0.95em; border: 1px solid ${isCorrect ? '#a3cfbb' : '#f5c6cb'};">
              ${resultText}
            </div>
          `;
          container.appendChild(card);
        });
      }

      // 文件导入功能
      document.getElementById("fileInput").addEventListener("change", (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function (event) {
          try {
            const importedQuestions = JSON.parse(event.target.result);

            // 简单验证是否是数组且包含必要字段
            if (!Array.isArray(importedQuestions) || !importedQuestions.every(q => q.questionName && q.options)) {
              throw new Error("文件结构无效");
            }

            // 更新当前 questions 数据
            questions = importedQuestions;
            renderQuestions(questions);

            // 可选：清空搜索框
            document.getElementById("searchInput").value = "";
            alert(`✅ 成功导入 ${questions.length} 道题目！`);
          } catch (err) {
            console.error("文件解析失败:", err);
            alert("❌ 文件解析失败，请上传有效的 JSON 题目文件！");
          }
        };

        reader.onerror = () => {
          alert("❌ 文件读取失败！");
        };

        reader.readAsText(file);
      });
    });
  </script>
</body>

</html>